package util

import (
	"gorm.io/gorm"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core"
	"likeadmin/core/response"
)

var SettingUtil = settingUtil{db: core.GetDB()}

// settingUtil 系统后台配置获取操作工具类
type settingUtil struct {
	db *gorm.DB
}

// getSettingVal
func (s settingUtil) getSettingVal(key string, name string, defaultVal string) string {
	val := RedisUtil.HGet(key, name)
	if val == "" {
		dbVal, _ := ConfigUtil.GetVal(s.db, key, name, defaultVal)
		RedisUtil.HSet(key, name, dbVal, -1)
		val = dbVal
	}
	return val
}

// getSettingStruct 获取配置
func (s settingUtil) getSettingStruct(key string, name string, res interface{}) (e error) {
	val := RedisUtil.HGet(key, name)

	if val == "" {
		str, err := ConfigUtil.GetVal(s.db, key, name, "")
		if e = response.CheckErr(err, "Detail GetVal err"); e != nil {
			return
		}
		if str == "" {
			return
		}
		RedisUtil.HSet(key, name, str, -1)
		val = str
	}
	e = response.CheckErr(ToolsUtil.JsonToObj(val, &res), "Detail JsonToObj err")
	return
}

// GetSmsEngine 获取短信引擎名称
func (s settingUtil) GetSmsEngine() string {
	return s.getSettingVal("sms", "default", "")
}

// GetSmsEngineConf 获取短信配置
func (s settingUtil) GetSmsEngineConf(engine string) (res *resp.SmsSettingResp) {
	_ = s.getSettingStruct("sms", engine, &res)
	return
}

// GetStorageEngine 获取默认存储引擎
func (s settingUtil) GetStorageEngine() string {
	return s.getSettingVal("storage", "default", "local")
}

// GetStorageEngineConf 获取存储引擎配置
func (s settingUtil) GetStorageEngineConf(engine string) (res *resp.StorageSettingResp) {
	_ = s.getSettingStruct("storage", engine, &res)
	return
}
